import { isRef, onMounted, ref, unref } from "@vue/composition-api";
import _ from "lodash";
import { request } from "../utils/request";

const useFetchOptions = {
  method: "get",
  immediate: true,
  params: {},
  data: {}
};

export const useFetch = (url, options = useFetchOptions) => {
  const { immediate, ...requestOptions } = {
    ...useFetchOptions,
    ...unref(options)
  };

  const loading = ref(false);
  const error = ref(null);
  const response = ref(null);

  async function fetch() {
    loading.value = true;
    error.value = null;
    response.value = null;

    console.debug(requestOptions);

    try {
      response.value = await request(
        url,
        _.mapValues(requestOptions, val => (isRef(val) ? val.value : val))
      );
    } catch (e) {
      console.error(e);
      error.value = e;
    } finally {
      loading.value = false;
    }
  }

  onMounted(() => {
    if (immediate) {
      fetch();
    }
  });

  return {
    loading,
    error,
    data: response,
    fetch
  };
};
